import java.util.Scanner;

/**
 * @program: data_structures_algorithms
 * @description:二维数组==>稀疏数组
 * @author: lld
 * @create: 2020/08/09 19:09
 **/
public class SparseArray1 {
    public static void main(String[] args) {
        int[][] a = new int[11][11];
        a[1][2] = 1;
        a[2][3] = 2;
        a[4][5] = 6;
        a[5][2] = 11;
        System.out.println("原二维数组：");
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                System.out.printf("%d\t", a[i][j]);
            }
            System.out.println();
        }
//        从二维数组转换为稀疏数组
        int n = 0;
//        获取非0数据个数
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                if (a[i][j] != 0) {
                    n++;
                }
            }
        }

        int[][] b = new int[n + 1][3];
        b[0][0] = 11;
        b[0][1] = 11;
        b[0][2] = n;
//        获取非0 数在数组中位置
        int count = 0;
        for (int i = 0; i < a.length; i++) {
            for (int j = 0; j < a[i].length; j++) {
                if (a[i][j] != 0) {
                    count++;
                    b[count][0] = i;
                    b[count][1] = j;
                    b[count][2] = a[i][j];
                }
            }
        }
        System.out.println("稀疏数组：");
        for (int i = 0; i < b.length; i++) {
            System.out.printf("%d\t%d\t%d\n", b[i][0], b[i][1], b[i][2]);
        }
//        从稀疏数组恢复二维数组
        int[][] a2 = new int[b[0][0]][b[0][1]];
        for (int i = 1; i < b.length; i++) {
            a2[b[i][0]][b[i][1]] = b[i][2];
        }
        System.out.println("从稀疏数组恢复二维数组:");
        for (int[] ints : a2) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }
    }
}
